package com.zhengsr.corelib.net.intecepter;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.zhengsr.CoreManager;
import com.zhengsr.corelib.utils.Contracts;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class SaveCookieIntecepter implements Interceptor {



    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();


        String cookie = getCookie(request.url().host());

        //本地已经存储，则从本地拿
        if (!TextUtils.isEmpty(cookie)) {
            Request.Builder builder = request.newBuilder();
            builder.addHeader("Cookie", cookie); //客户端，Header 中Cookie 关键字
            return chain.proceed(builder.build());
        }else {
            //服务端中取出 Set-Cookie 关键字中的信息
            Response response = chain.proceed(request);
            List<String> cookies = response.headers("Set-Cookie");
            if (!cookies.isEmpty()) {
                String str = encodeString(cookies);
                saveCookieString(request.url().host(), str);
            }
            return response;
        }

    }


    /**
     * 把header中，所有的cookie统一成一个字符串
     * @param cookieStrings
     * @return
     */
    private String encodeString(List<String> cookieStrings){
        List<String> lists = new ArrayList<>();
        //把所有的 cookie 字符串，统一放到 lists 中，用;分割出所有的字符
        for (String string : cookieStrings) {
            String[] cookies = string.split(";");
            for (String cookieString : cookies) {
                lists.add(cookieString);
            }
        }

        StringBuilder sb = new StringBuilder();
        //再从 lists 中取出所有，然后放在统一的字符串中，用 ; 隔开
        int count = lists.size();
        for (int i = 0; i < count; i++) {
            String str = lists.get(i);
            if (i != count - 1){
                sb.append(str).append(";");
            }else{
                sb.append(str);
            }
        }
        return sb.toString();
    }

    /**
     * 保存cookie字符在本地中
     * @param host
     * @param str
     */
    private void saveCookieString(String host, String str) {
        SharedPreferences.Editor editor = CoreManager.getContext()
                .getSharedPreferences(Contracts.COOKIE_SPREF, Context.MODE_PRIVATE).edit();
        if (!str.isEmpty()){
            editor.putString(host,str);
        }
        editor.apply();
    }

    /**
     * 从本地拿出cookie字符
     * @param host
     * @return
     */
    private String getCookie(String host) {

        SharedPreferences sp = CoreManager.getContext().getSharedPreferences(Contracts.COOKIE_SPREF,
                Context.MODE_PRIVATE);

        String cookie = sp.getString(host, "");
        return cookie;
    }
}
